package com.binsoft.ndtta;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

public class MyWidgetProvider extends AppWidgetProvider
{
	private static final String TAG = "MyWidgetProvider";
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) 
	{	
		SharedPreferences prefs = context.getApplicationContext().getSharedPreferences(Constants.PREFS , Context.MODE_PRIVATE );		
		int team = prefs.getInt(Constants.TEAM_PREF,-1);
		int division = prefs.getInt(Constants.DIVISION_PREF,-1);		
		byte[] key = null;
		try
		{
			key = prefs.getString( Constants.ENCRYPTION_STRING, null).getBytes( "UTF-8");
		} 
		catch (UnsupportedEncodingException e)
		{
		}
		
		if ( team != -1 && division != -1 )
		{
			for ( int widgetId : appWidgetIds )
			{
				MyWidgetProvider.updateAppWidget(context, appWidgetManager, widgetId, division, team, key );
			}
		}
	}

	private static void encryptTeams( Team[] teams, byte[] key )
	{
		for ( Team t : teams )
		{
			TeamContact contact = t.contact();

			if (null != contact)
			{
				try
				{
					// Store the key for use later.
					contact.key(key);
					
					if (contact.name().length() > 0)
					{	
						contact.name(Encryptor.encrypt(contact.name().getBytes("UTF-8"), Constants.DECRYPTOR));
					}
	
					if (contact.mobile().length() > 0)
					{
						contact.mobile(Encryptor.encrypt(contact.mobile().getBytes("UTF-8"), Constants.DECRYPTOR));
					}
	
					if (contact.work().length() > 0)
					{
						contact.work(Encryptor.encrypt(contact.work().getBytes("UTF-8"), Constants.DECRYPTOR));
					}
	
					if (contact.landline().length() > 0)
					{
						contact.landline(Encryptor.encrypt(contact.landline().getBytes("UTF-8"), Constants.DECRYPTOR));
					}
	
					if (contact.email().length() > 0)
					{
						contact.email(Encryptor.encrypt(contact.email().getBytes("UTF-8"), Constants.DECRYPTOR));
					}
				}
				catch ( UnsupportedEncodingException e )
				{
					
				}
			}
		}	
	}
	
	public static void updateAppWidget(Context context,
			AppWidgetManager appWidgetManager, int appWidgetId, int division, int team, byte[] key ) 
	{
	
		RemoteViews updateViews = new RemoteViews(context.getPackageName(),R.layout.main);

		Intent intent = new Intent(context, MainActivity.class);
		intent.putExtra(Constants.TEAM_INTENT_EXTRA, team );
		intent.putExtra(Constants.DIVISION_INTENT_EXTRA, division );
		intent.putExtra( Constants.ENCRYPTION_KEY_EXTRA, key );
		
		// Time Now.
		GregorianCalendar now = new GregorianCalendar();
		
		int startingWeek = Constants.START_DATE.get( Calendar.WEEK_OF_YEAR );
		int currentWeek = now.get( Calendar.WEEK_OF_YEAR );

		int week = startingWeek;
		
		if ( currentWeek < startingWeek )
		{
			week = 52 - startingWeek + currentWeek;
		}
		
		boolean useMatchDate = false;
		
		if ( week < 0 )
		{
			useMatchDate = true;
			week = 0;
		}
		
		intent.putExtra(Constants.WEEK_INTENT_EXTRA, week);
		PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		updateViews.setOnClickPendingIntent(R.id.dateField, pi);

		// Encrypt the teams with our known key.
		encryptTeams( Constants.div1, key );
		encryptTeams( Constants.div2, key );
		encryptTeams( Constants.div3, key );
		
		Log.i( TAG, "Attempting to get match for week:" + week + " and team:" + team );
		
		Match match = Matches.getMatch(week, team );
		Team homeTeam = null;
		Team awayTeam = null;
		
		Log.i( TAG, "Got match for week:" + match );
		
		if ( null != match )
		{
			homeTeam = Matches.getTeam(division, match.home());
			awayTeam = Matches.getTeam(division, match.away());
		}
		
		// Setup a pending intent for the map view.
		if ( null != homeTeam )
		{
			updateViews.setViewVisibility(R.id.versusField, View.VISIBLE);

			if ( !homeTeam.name().isEmpty() )
			{
				Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + homeTeam.latitude() + "," + homeTeam.longitude())); 
		
				PendingIntent pi2 = PendingIntent.getActivity(context, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
				updateViews.setOnClickPendingIntent(R.id.mapImageView, pi2);
			
				// Setup a pending event for the home team field
				final Intent teamIntent = new Intent( context, TeamViewActivity.class );
				teamIntent.putExtra( Constants.TEAM_INTENT_EXTRA, match.home() );
				teamIntent.putExtra( Constants.DIVISION_INTENT_EXTRA, division );
				teamIntent.putExtra( Constants.ENCRYPTION_KEY_EXTRA, key );
				PendingIntent pendingTeamIntent = PendingIntent.getActivity(context, 0, teamIntent, PendingIntent.FLAG_UPDATE_CURRENT);
				updateViews.setOnClickPendingIntent(R.id.homeTeamField, pendingTeamIntent);
				updateViews.setTextViewText(R.id.homeTeamField, homeTeam.name() );
			}
			else
			{
				updateViews.setTextViewText(R.id.homeTeamField, "BYE");
			}
		}
		else
		{
			if ( null != match )
			{
				updateViews.setTextViewText(R.id.homeTeamField, match.description() );
			}
			else
			{
				updateViews.setTextViewText(R.id.homeTeamField, "No match scheduled");
			}
			
			updateViews.setViewVisibility(R.id.versusField, View.GONE);
		}
		
		if ( null != awayTeam )
		{
			updateViews.setViewVisibility(R.id.versusField, View.VISIBLE);

			if ( !awayTeam.name().isEmpty() )
			{
				// Setup a pending event for the away team field
				final Intent awayTeamIntent = new Intent( context, TeamViewActivity.class );
				awayTeamIntent.putExtra( Constants.TEAM_INTENT_EXTRA, match.away() );
				awayTeamIntent.putExtra( Constants.DIVISION_INTENT_EXTRA, division );
				awayTeamIntent.putExtra( Constants.ENCRYPTION_KEY_EXTRA, key );
				PendingIntent pendingAwayTeamIntent = PendingIntent.getActivity(context, 1, awayTeamIntent, PendingIntent.FLAG_UPDATE_CURRENT);
				updateViews.setOnClickPendingIntent(R.id.awayTeamField, pendingAwayTeamIntent);
				updateViews.setTextViewText(R.id.awayTeamField, awayTeam.name() );
			}
			else
			{
				updateViews.setTextViewText(R.id.awayTeamField, "BYE");
			}
		}
		else
		{
			updateViews.setTextViewText(R.id.awayTeamField, "");
			updateViews.setViewVisibility(R.id.versusField, View.GONE);
		}
		
		// Hide the previous score layout.
		NdttaDatabaseAdapter adapter = new NdttaDatabaseAdapter(context);
		adapter.open();
		Cursor previousMatch = null;
		
		if ( null != match )
		{
			previousMatch = adapter.fetchMatch( match,true,false );
		}
		
		// Close the database
		adapter.close();
		
		if ( previousMatch != null && previousMatch.getCount() > 0 )
		{
			int homeScoreCol = previousMatch.getColumnIndex("homescore");
			int awayScoreCol = previousMatch.getColumnIndex("awayscore");
			
			int homeScore = previousMatch.getInt( homeScoreCol );
			int awayScore = previousMatch.getInt( awayScoreCol );

			updateViews.setTextViewText(R.id.prevHomeScore,"(" + awayScore + ")" );
			updateViews.setTextViewText(R.id.prevAwayScore,"(" + homeScore + ")" );
			
			updateViews.setViewVisibility(R.id.prevHomeScore, View.VISIBLE );
			updateViews.setViewVisibility(R.id.prevAwayScore, View.VISIBLE );
		}
		else
		{
			updateViews.setViewVisibility(R.id.prevHomeScore, View.GONE );
			updateViews.setViewVisibility(R.id.prevAwayScore, View.GONE );
		}
		
		// Now work out the difference between home night and the monday.
		int homeNight = Calendar.MONDAY;
		
		if ( null != homeTeam )
		{
			homeNight = homeTeam.homeNight();
		}

		SimpleDateFormat format = new SimpleDateFormat(Constants.DATE_FORMAT, Locale.UK );
		String dateStr = "";
		
		if ( useMatchDate )
		{
			GregorianCalendar cal = new GregorianCalendar();
			cal.setTime( Constants.START_DATE.getTime() );
			cal.roll( Calendar.WEEK_OF_YEAR, match.week() );
			cal.roll( Calendar.DAY_OF_WEEK, homeNight - Calendar.MONDAY );
			dateStr = format.format( cal.getTime() );
		}
		else
		{
			now.roll( Calendar.DAY_OF_WEEK, homeNight - Calendar.MONDAY - 
					( now.get(Calendar.DAY_OF_WEEK ) - Calendar.MONDAY));
		
			dateStr = format.format( now.getTime() ); 
		}

		updateViews.setTextViewText(R.id.dateField, dateStr );
		
		appWidgetManager.updateAppWidget(appWidgetId, updateViews);
	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) 
	{
		super.onDeleted(context, appWidgetIds);
	}

}
